<?php

namespace App\Http\Controllers\PrizePayment;

use App\App\Services\WechatService;
use App\Http\Controllers\Controller;
use App\Models\Prize\PrizeService;
use App\Models\PrizePayment\PrizePayment;
use App\Models\PrizePayment\PrizePaymentService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class WeChatController extends Controller
{
    /**
     * @param WechatService $service
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function notify(Request $request, WechatService $service)
    {
        Log::info($request->getContent());

        return $service->notify();
    }

    /**
     * @param Request $request
     * @param WechatService $service
     *
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function pay(Request $request, WechatService $service, PrizeService $prizeService, PrizePaymentService $prizePaymentService)
    {
        $this->validate($request, [
            'order_id' => 'required|string',
        ], [
            'stock_number.required' => '订单号不能为空',
        ]);

        $orderId = $request->query->get('order_id');
        $paymentInfo = $prizePaymentService->find(['order_id' => $orderId]);
        if (!empty($paymentInfo) && !$paymentInfo->isUnpaid()) {
            return view('web.prizePayment.wechatPay', ['message' => '订单不能提交', 'orderId' => $orderId]);
        }
        $money = $paymentInfo['price'] * $paymentInfo['number'];
        $resultData = $service->prepareOrder($paymentInfo['order_id'], $paymentInfo['prize_id'], $money, 'NATIVE', $paymentInfo['order_name']);
        if (!$resultData) {
            return view('web.prizePayment.wechatPay', ['error' => '生成微信订单失败，请稍候再试', 'orderId' => $orderId]);
        }
        $prepareData = $resultData['prepare'];
        $order = $resultData['order'];
        $paymentInfo->commited();
        Log::debug('微信发起支付:' . $prepareData->code_url);

        return view('web.prizePayment.wechatPay', ['url' => $prepareData->code_url, 'orderId' => $order->out_trade_no]);
    }
}
